package com.ys.web.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.UUID;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSON;
import com.ys.extend.utils.ContextHolderUtils;
import com.ys.web.dao.CommonDao;
import com.ys.web.pojo.BackupInfo;
import com.ys.web.pojo.CompanyInfo;
import com.ys.web.service.AccountService;
import com.ys.web.service.BackupService;
import com.ys.web.service.CompanyService;
import com.ys.web.service.ImportBaiduCSVService;

@Scope("prototype")
@Controller
public class UploadController extends HttpServlet{

	private String uploadPath;
	private String extensions;
	private static final ResourceBundle bundle = ResourceBundle.getBundle("upload");

	@Autowired
	CompanyService companyService;

	@Autowired
	AccountService accountService;

	@Autowired
	ImportBaiduCSVService importBaiduCSVService;
	
	@Autowired
	BackupService backupService;
	
	@RequestMapping(value = "getFileUrl.do", method = RequestMethod.POST)
	public void getFileUrl(HttpServletRequest request, HttpServletResponse response) throws IOException {
		 String filename = request.getParameter("filename");  
		 response.setContentType(getServletContext().getMimeType(filename));  
	        //设置Content-Disposition  
	        response.setHeader("Content-Disposition", "attachment;filename="+filename);  
	        //读取目标文件，通过response将目标文件写到客户端  
	        //获取目标文件的绝对路径  
	        String fullFileName = getServletContext().getRealPath("/download/" + filename);  
	        //System.out.println(fullFileName);  
	        //读取文件  
	        InputStream in = new FileInputStream(fullFileName);  
	        OutputStream out = response.getOutputStream();  
	}
	
	@RequestMapping(value = "downloadFile.do", method = RequestMethod.POST)
	public void downloadFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setCharacterEncoding("UTF-8");
		String companyId = request.getParameter("companyId");// 获取公司id
	}

	@RequestMapping(value = "uploadFile.do", method = RequestMethod.POST)
	public void uploadFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		response.setCharacterEncoding("UTF-8");

		String companyId = request.getParameter("companyId");// 获取公司id
		String accountId = request.getParameter("accountId");// 获取账户id
		String reportType = request.getParameter("reportType");// 获取报告类型：searchReport【搜索词报告】，originalityReport【创意报告】

		Integer userId = null;

		Integer companyIdNum = null;
		Integer accountIdNum = null;
		if (ContextHolderUtils.getSession().getAttribute("userId") != null) {
			try {
				userId = (Integer) ContextHolderUtils.getSession().getAttribute("userId");

			} catch (Exception e) {
				response.getWriter().write("没有权限");
				return;
			}

			if (companyId != null && accountId != null) {

				try {
					companyIdNum = Integer.valueOf(companyId);
					accountIdNum = Integer.valueOf(accountId);
				} catch (Exception e) {
					response.getWriter().write("错误的参数类型");
					return;
				}

				Integer chunk = null; /* 分割块数 */
				Integer chunks = null; /* 总分割数 */
				String tempFileName = null; /* 临时文件名 */
				String newFileName = null; /* 最后合并后的新文件名 */
				String[] extensionsArray = null;/* 要过滤的扩展名数组 */
				BufferedOutputStream outputStream = null;
				uploadPath = bundle.getString("uploadPath");
				extensions = bundle.getString("extensions");

				File up = new File(uploadPath);

				if (!up.exists()) {
					up.mkdir();
				}
				// 判断文件是否文件

				if (ServletFileUpload.isMultipartContent(request)) {

					try {

						DiskFileItemFactory factory = new DiskFileItemFactory();
						factory.setSizeThreshold(1024);// 设置流的每次读取大小，相当于bufferStream
						ServletFileUpload upload = new ServletFileUpload(factory);
						upload.setHeaderEncoding("UTF-8");
						upload.setSizeMax(5 * 1024 * 1024);// 设置附件最大大小，超过这个大小上传会不成功
															// 5m*/
						List<FileItem> items = upload.parseRequest(request);// 分割文件请求
						// MultipartHttpServletRequest multHttpServletRequest =
						// (MultipartHttpServletRequest)request;

						// System.out.println("item:"+items.size());
						for (FileItem item : items) {
							// System.out.println("go");
							if (item.isFormField()) {// 判断该表单项是否是普通类型
								if (item.getFieldName().equals("name")) {
									System.out.println("tempFileName1:" + tempFileName);
									tempFileName = item.getString();
									System.out.println("临时文件名：" + tempFileName);
								} else if (item.getFieldName().equals("chunk")) {
									System.out.println("tempFileName2:" + tempFileName);
									chunk = Integer.parseInt(item.getString());
									System.out.println("当前文件块：" + (chunk + 1));
								} else if (item.getFieldName().equals("chunks")) {
									System.out.println("tempFileName3:" + tempFileName);
									chunks = Integer.parseInt(item.getString());
									System.out.println("文件总分块：" + chunks);
								}
							} else {
								System.out.println("tempFileName4:" + tempFileName);
								if (tempFileName != null) {
									String chunkName = tempFileName;
									if (extensions != null) {
										extensionsArray = extensions.split(",");
										String es = FilenameUtils.getExtension(tempFileName);
										boolean extensionExists = false;
										for (String extension : extensionsArray) {
											if (extension.equals(FilenameUtils.getExtension(tempFileName))) {//将upload.properties文件的extension的后缀名数组逐个与当前文件后缀对比
												// Map<String, Object> m = new
												// HashMap<String, Object>();
												// m.put( "status", false );
												// m.put("message",
												// "请上传正确的文件类型");
												// response.getWriter().write(
												// JSON.toJSONString( m ) );
												// return;
												extensionExists = true;
											}

										}
										
										//当前文件后缀与upload.properties文件的extension的后缀不匹配
										if (extensionExists == false) {
											Map<String, Object> m = new HashMap<String, Object>();
											m.put("status", false);
											m.put("message", "请上传正确的文件类型");
											response.getWriter().write(JSON.toJSONString(m));
											return;
										}
									}
									if (chunkName != null) {
										chunkName = chunk + "_" + tempFileName;
									}

									File saveFile = new File(uploadPath, chunkName);
									System.out.println(saveFile.getAbsolutePath());
									item.write(saveFile);

								} // 写入文件块
							}

						}
						if (tempFileName == null) {
							Map<String, Object> m = new HashMap<String, Object>();
							m.put("status", false);
							m.put("message", "上传不成功");
							response.getWriter().write(JSON.toJSONString(m));
							return;

						}
						// System.out.println("tempFileName:"+tempFileName);
						newFileName = UUID.randomUUID().toString().replace("-", "").concat(".")
								.concat(FilenameUtils.getExtension(tempFileName));

						if (chunk != null && chunk + 1 == chunks) {
							File uploadFile = new File(uploadPath, newFileName);
							outputStream = new BufferedOutputStream(new FileOutputStream(uploadFile));
							// 输建一个文件对象，根据文件对象输建一个文件输出流，把文件输出流转化为缓冲流
							/* 遍历文件块合并 */
							for (int i = 0; i < chunks; i++) {
								// 创建临时文件对象
								File tempFile = new File(uploadPath, i + "_" + tempFileName);
								// 临时文件转成字节流
								byte[] bytes = FileUtils.readFileToByteArray(tempFile);
								outputStream.write(bytes);// 把字节流按序写入
								outputStream.flush();// 刷新缓存
								tempFile.delete();// 删除临时文件
							}

							outputStream.flush();// 合并所有后刷新缓存
						}

						Map<String, Object> m = new HashMap<String, Object>();
						String filePath = bundle.getString("uploadPath") + File.separatorChar + newFileName;
						m.put("status", true);
						m.put("fileUrl", filePath);
						m.put("message", "上传成功");
						response.getWriter().write(JSON.toJSONString(m));

						//csv文件导入数据库
						if("searchReport".equals(reportType)) {
							importBaiduCSVService.readBaiduCSVToDB(filePath, Charset.forName("GBK"), userId, companyIdNum,accountIdNum);
						} else if ("originalityReport".equals(reportType)) {
							importBaiduCSVService.readBaiduOriginalityToDB(filePath, Charset.forName("GBK"), userId);
						}
						
						
						

					} catch (FileUploadException e) {
						e.printStackTrace();
						Map<String, Object> m = new HashMap<String, Object>();
						m.put("status", false);
						response.getWriter().write(JSON.toJSONString(m));
					} catch (Exception e) {
						e.printStackTrace();
						Map<String, Object> m = new HashMap<String, Object>();
						m.put("status", false);
						response.getWriter().write(JSON.toJSONString(m));
					} finally {
						try {
							if (outputStream != null)
								outputStream.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}

			}

		}
	}
}
